import { StorageKey } from '@/constants/storage-key';
import { IPlank } from '@/types';
import { Button, Modal, message } from 'antd';
import { useModel } from 'umi';

export function Reset() {
  const { setPlank, plank, getOldPlank } = useModel('bom');
  async function onReset() {
    Modal.confirm({
      title: '确认要恢复至初始版本吗？',
      content: '确认后将使用最初版本的物料数据覆盖当前数据',
      onOk: async () => {
        if (!plank) return;
        const { plankId: id } = plank;
        let resetData = await getBomResetData(id);
        if (!resetData) {
          const oldPlank = getOldPlank(id);
          await setBomResetData(oldPlank);
          resetData = oldPlank;
        }
        setPlank(resetData as IPlank);
        message.success('已恢复至初始版本，待保存后更新数据');
      },
    });
  }

  return (
    <>
      <Button onClick={onReset}>恢复初始版本</Button>
    </>
  );
}

export function getBomResetKey(id: string) {
  return `${StorageKey.BomReset}-${id}`;
}

export const getBomResetData = (id: string) =>
  Manycore.Storage.Enterprise.getItemAsync(
    getBomResetKey(id),
  ) as Promise<IPlank>;

export const setBomResetData = (plank: IPlank) =>
  Manycore.Storage.Enterprise.putItemAsync({
    key: getBomResetKey(plank.plankId),
    value: plank,
  });
